/**
 * UserSettingServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.util.Iterator;

import org.jackysoft.entity.User;
import org.jackysoft.entity.UserSetting;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.UserSettingService;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserSettingServiceImpl extends AbstractStringIdServiceImpl<UserSetting> implements
		UserSettingService {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7483374970916305272L;

	public UserSettingServiceImpl(){
	    this.type = UserSetting.class;
	}
	
	

    

  
	
	@Override
	public void create(UserSetting bean) throws DataAccessException{
		UserSetting dest = getByOwner(bean.getOwner());
		if(dest!=null){
			BeanUtils.copyProperties(bean, dest,new String[]{"id"});
			update(dest);
		}else{
	        super.create(bean);
		}
	}

  

	@Override
	public UserSetting getByOwner(User owner) throws DataAccessException {
	    String qs = fromSelect(" us where us.owner=:owner ");
	    Iterator itr = getSession().createQuery(qs).setParameter("owner", owner).iterate();
		return (UserSetting) (itr.hasNext()?itr.next():null);
	}







	@Override
	@Transactional(
			propagation=Propagation.REQUIRES_NEW,
			isolation=Isolation.SERIALIZABLE)
	public void removeByOwner(User owner) throws DataAccessException {
		String hql =String.format("delete from %s us where us.owner.username='%s' ",entitytable(),owner.getUsername());
		query(hql).executeUpdate();		
	}
	
	
	
		
}